
from util import ReadFile, WriteFile


from xyztools import extractXYZLine


def invFile(filenameIn, filenameOut):
          
    data = ReadFile(filenameIn)
    dataLines = [l for l in data.split("\n") if l.strip() and not l.strip().startswith("#") ]
    CommentLines = [l for l in data.split("\n") if l.strip() and l.strip().startswith("#") ]
    
    outData = CommentLines

    # Ok, we have no positive x's:
    for l in dataLines:
        i,t,x,y,z,X,Y,Z,p = extractXYZLine(l)
        x = x * -1
        X = X * -1
        outData.append( "\t".join( [str(g) for g in [i,t,x,y,z,X,Y,Z,p] ] ) )
    WriteFile( filenameOut, "\n".join( outData) )
        

def nrnInvertX( nsFilenameSrc, nrnFilenameSrc,nsFilenameSink, nrnFilenameSink):

    print " -- Checking if we need to invert?",
    # Find the amount of translation we need to do!
    
    # Check ns file only
    data = ReadFile(nsFilenameSrc)
    datanrn = ReadFile(nrnFilenameSrc)
    dataLines = [l for l in data.split("\n") if l.strip() and not l.strip().startswith("#") ]
    CommentLines = [l for l in data.split("\n") if l.strip() and l.strip().startswith("#") ]
    
    # Check x values for T = 14 only and then check if T=14 xmin < -1500. If it is then 
    # invert all x values in both ns and nrn file
    xmin,xmax = None,None
    for l in dataLines:
        i,t,x,y,z,X,Y,Z,p = extractXYZLine(l)
        
        if t == 14:
            #print t
            #print xmin
            #print xmax
            xmin = min( [xmin,x,X] ) if xmin != None else min( [x,X] )
            xmax = max( [xmax,x,X] ) if xmax != None else max( [x,X] )

    if (xmin <= -1500 ):
        print "  Yes, xmin,max:", xmin,xmax
        invFile(nsFilenameSrc, nsFilenameSink)
        invFile(nrnFilenameSrc, nrnFilenameSink)
        
    else:
        print "  No, xmin,max:", xmin,xmax
        WriteFile(nsFilenameSink, data)
        WriteFile(nrnFilenameSink, datanrn)